<script setup>
import { ref, watch } from "vue";
import {
  addBookService,
  listBooksService,
  updateBookService,
  deleteBookService,
} from "@/api/books.js";
import {
  queryLikeBookDescriptionByIsbnService,
  queryBookDescriptionByIsbnService,
  deleteBookDescriptionService,
} from "@/api/bookdescription.js";
import { ElMessage, ElMessageBox } from "element-plus";

const booksData = ref([]);
const pageNum = ref(1);
const pageSize = ref(15);
const total = ref(10);
const showAddDialog = ref(false);
const showUpdateDialog = ref(false);
const addFormRef = ref(null);
const updateFormRef = ref(null);
const selectedBooks = ref([]);

const newBook = ref({
  bookName: "",
  description: "",
  price: "",
  language: "",
  isbn: "",
  status: "未借阅",
  quantity: 1,
  shelfTime: "",
});

const searchBook = ref({
  bookId: "",
  bookName: "",
  description: "",
  price: "",
  language: "",
  isbn: "",
  status: "",
});

const isbnSuggestions = ref([]);

const handleSizeChange = (size) => {
  pageSize.value = size;
  listBooks();
};
const handleCurrentChange = (num) => {
  pageNum.value = num;
  listBooks();
};

const listBooks = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...searchBook.value,
  };
  let result = await listBooksService(params);
  total.value = result.data.total;
  booksData.value = result.data.records;
};

const reset = async () => {
  searchBook.value.bookId = "";
  searchBook.value.bookName = "";
  searchBook.value.description = "";
  searchBook.value.price = "";
  searchBook.value.language = "";
  searchBook.value.isbn = "";
  searchBook.value.status = "";
  await listBooks();
};

const addBook = async () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      let bookData = {
        isbn: newBook.value.isbn,
        status: newBook.value.status,
        quantity: parseInt(newBook.value.quantity, 10),
      };
      let bookResult = await addBookService(bookData);
      if (bookResult.code === 0) {
        showAddDialog.value = false;
        ElMessage.success("新增成功");
        await listBooks();
      }
    }
  });
};

const updateBook = async () => {
  updateFormRef.value.validate(async (valid) => {
    if (valid) {
      let updateResult = await updateBookService(newBook.value);
      if (updateResult.code === 0) {
        showUpdateDialog.value = false;
        ElMessage.success("更新成功");
        await listBooks();
      } else {
        ElMessage.error("更新失败");
      }
    }
  });
};

const deleteBook = async (bookId) => {
  ElMessageBox.confirm("此操作将永久删除该书籍, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let deleteResult = await deleteBookService(bookId);
      if (deleteResult.code === 0) {
        ElMessage.success("删除成功");
        await listBooks();
      } else {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const confirmBatchDelete = () => {
  ElMessageBox.confirm("此操作将永久删除选中的书籍, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      for (let book of selectedBooks.value) {
        await deleteBookService(book.bookId);
      }
      ElMessage.success("批量删除成功");
      await listBooks();
    })
    .catch(() => {
      ElMessage.info("已取消批量删除");
    });
};

// const viewDetails = (row) => {
//   newBook.value = { ...row };
//   showUpdateDialog.value = true;
// };

const viewAdd = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  newBook.value = {
    bookName: "",
    description: "",
    price: "",
    language: "",
    isbn: "",
    status: "未借阅",
    quantity: 1,
  };
  showAddDialog.value = true;
};

const viewUpdate = (row) => {
  if (updateFormRef.value) {
    updateFormRef.value.resetFields();
  }
  newBook.value = { ...row };
  showUpdateDialog.value = true;
};

const queryBookDescriptionByIsbn = async (queryString, cb) => {
  // if (queryString.length < 1) {
  //   isbnSuggestions.value = [];
  //   cb([]);
  //   return;
  // }
  try {
    const result = await queryLikeBookDescriptionByIsbnService(queryString);
    if (result.code === 0) {
      isbnSuggestions.value = result.data.map((book) => ({ value: book.isbn }));
      if (isbnSuggestions.value.length === 0) {
        ElMessage.error("未匹配到正确的IBSN，请输入正确的IBSN或先插入");
      }
      cb(isbnSuggestions.value);
      if (result.data.length === 1 && result.data[0].isbn === queryString) {
        newBook.value.bookName = result.data[0].bookName;
        newBook.value.description = result.data[0].description;
        newBook.value.price = result.data[0].price;
        newBook.value.language = result.data[0].language;
      } else {
        newBook.value.bookName = "";
        newBook.value.description = "";
        newBook.value.price = "";
        newBook.value.language = "";
      }
    } else {
      console.error("Error fetching ISBN suggestions: ", result.message);
    }
  } catch (error) {
    console.error("Error in queryBookDescriptionByIsbn: ", error);
  }
};

const handleSelect = async (item) => {
  try {
    console.log("item:", item);
    const result = await queryBookDescriptionByIsbnService(item.value); // 使用选中的isbn值进行查询
    if (result.code === 0) {
      newBook.value.bookName = result.data.bookName;
      newBook.value.description = result.data.description;
      newBook.value.price = result.data.price;
      newBook.value.language = result.data.language;
    } else {
      console.error(
        "Error fetching book description by ISBN: ",
        result.message,
      );
    }
  } catch (error) {
    console.error("Error in handleSelect: ", error);
  }
};

const handleSelectionChange = (val) => {
  selectedBooks.value = val;
};

watch(
  () => newBook.value.isbn,
  (newVal) => {
    if (newVal.length === 0) {
      // 清空字段
      newBook.value.bookName = "";
      newBook.value.description = "";
      newBook.value.price = "";
      newBook.value.language = "";
    }
  },
);

const statusCellStyle = ({ row, column }) => {
  if (column.property === "status") {
    switch (row.status) {
      case "未借阅":
        // 设置为50%透明度
        return { backgroundColor: "rgba(133, 206, 97, 0.3)" };
      case "已借阅":
        // 设置为50%透明度
        return { backgroundColor: "rgba(247, 137, 137, 0.3)" };
      default:
        // 设置为50%透明度
        return { backgroundColor: "rgba(235, 181, 99, 0.3)" };
    }
  }
};

const filterHandler = (value, row, column) => {
  const property = column.property;
  return row[property] === value;
};
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return "";
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}:${month}:${day}-${hours}:${minutes}:${seconds}`;
};

const rulesadd = {
  isbn: [
    { required: true, message: "请输入书籍ISBN", trigger: "blur" },
    { pattern: /^[0-9]+$/, message: "ISBN格式不正确", trigger: "blur" },
  ],
  status: [{ required: true, message: "请输入书籍状态", trigger: "blur" }],
  quantity: [{ required: true, message: "请输入书籍数量", trigger: "blur" }],
};
const rulesupdate = {
  isbn: [
    { required: true, message: "请输入书籍ISBN", trigger: "blur" },
    { pattern: /^[0-9]+$/, message: "ISBN格式不正确", trigger: "blur" },
  ],
  status: [{ required: true, message: "请输入书籍状态", trigger: "blur" }],
};

listBooks();
</script>

<template>
  <div class="search-container">
    <el-input
      v-model="searchBook.bookId"
      placeholder="请输入书籍ID"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.bookName"
      placeholder="请输入书籍名称"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.description"
      placeholder="请输入书籍描述"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.price"
      placeholder="请输入书籍价格"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.language"
      placeholder="请输入书籍语言"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.isbn"
      placeholder="请输入书籍ISBN"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.status"
      placeholder="请输入书籍状态"
      clearable
      class="search-input"
    />
  </div>
  <div class="button-group">
    <div class="extra-buttons">
      <el-button
        type="danger"
        @click="confirmBatchDelete"
        :disabled="selectedBooks.length === 0"
        icon="RemoveFilled"
        >批量删除</el-button
      >
    </div>
    <el-button @click="listBooks" type="primary" icon="Search">搜索</el-button>
    <el-button @click="reset" type="warning" icon="RefreshRight"
      >重置</el-button
    >
    <el-button type="success" @click="viewAdd" icon="CirclePlus"
      >新增书籍</el-button
    >
  </div>

  <el-table
    :data="booksData"
    :cell-style="statusCellStyle"
    :header-cell-style="{ background: '#2a598a', color: '#ffffff' }"
    border
    stripe
    :max-height="500"
    style="width: 100%"
    highlight-current-row
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="40" />
    <el-table-column fixed sortable prop="bookId" label="图书ID" width="120" />
    <el-table-column sortable prop="bookName" label="书名" min-width="120" />
    <el-table-column sortable prop="description" label="描述" min-width="120" />
    <el-table-column sortable prop="price" label="价格" min-width="120" />
    <el-table-column
      sortable
      min-width="120"
      prop="language"
      label="语言"
      :filters="[
        { text: '中文', value: '中文' },
        { text: '外文', value: '外文' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column sortable min-width="140" prop="isbn" label="ISBN" />
    <el-table-column
      sortable
      min-width="130"
      prop="shelfTime"
      label="上架时间"
      :formatter="formatDate"
    />
    <el-table-column
      sortable
      prop="status"
      label="状态"
      min-width="120"
      :filters="[
        { text: '已借阅', value: '已借阅' },
        { text: '未借阅', value: '未借阅' },
        { text: '丢失', value: '丢失' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column label="操作" align="center" fixed="right" width="220">
      <template #default="scope">
        <el-button type="warning" @click="viewUpdate(scope.row)" icon="Refresh"
          >更新</el-button
        >
        <el-button
          type="danger"
          @click="deleteBook(scope.row.bookId)"
          icon="delete"
        >
          删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="pageNum"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20, 30, 50, 100]"
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 20px; justify-content: flex-end"
  />

  <el-dialog title="新增书籍" v-model="showAddDialog" width="500">
    <el-form :model="newBook" :rules="rulesadd" ref="addFormRef">
      <el-form-item label="书名">
        <el-input v-model="newBook.bookName" disabled></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="newBook.description" disabled></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="newBook.price" disabled></el-input>
      </el-form-item>
      <el-form-item label="语言">
        <el-input v-model="newBook.language" disabled></el-input>
      </el-form-item>
      <el-form-item label="ISBN" prop="isbn">
        <el-autocomplete
          v-model="newBook.isbn"
          :fetch-suggestions="queryBookDescriptionByIsbn"
          placeholder="请输入书籍ISBN"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="newBook.status">
          <el-radio value="未借阅">未借阅</el-radio>
          <el-radio value="已借阅">已借阅</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input v-model="newBook.quantity"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="addBook">确定</el-button>
    </span>
  </el-dialog>

  <el-dialog title="更新书籍" v-model="showUpdateDialog" width="500">
    <el-form :model="newBook" :rules="rulesupdate" ref="updateFormRef">
      <el-form-item label="书名">
        <el-input v-model="newBook.bookName" disabled></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="newBook.description" disabled></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="newBook.price" disabled></el-input>
      </el-form-item>
      <el-form-item label="语言">
        <el-input v-model="newBook.language" disabled></el-input>
      </el-form-item>
      <el-form-item label="ISBN" prop="isbn">
        <el-autocomplete
          v-model="newBook.isbn"
          :fetch-suggestions="queryBookDescriptionByIsbn"
          placeholder="请输入书籍ISBN"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item label="上架时间" prop="language">
        <el-date-picker
          v-model="newBook.shelfTime"
          type="date"
          placeholder="请选择上架日期"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="newBook.status">
          <el-radio value="未借阅">未借阅</el-radio>
          <el-radio value="已借阅">已借阅</el-radio>
          <el-radio value="丢失">丢失</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showUpdateDialog = false">取消</el-button>
      <el-button type="primary" @click="updateBook">确定</el-button>
    </span>
  </el-dialog>
</template>

<style scoped></style>
